<template>
  <div>
    <a-card class="card">
      <template slot="title" >
        <span style="display:flex;align-items: center;">
          起量计划
          <a-tooltip style="margin-left:6px;">
            <template slot="title">
              之前销量为零，当日总订单大于等于3单
            </template>
            <a-icon style="cursor: pointer;" type="exclamation-circle" :style="{ fontSize: '12px',color:'#888888' }"/>
          </a-tooltip>
        </span>
      </template>
      <a-select v-model="optimizer" @change="selectChange" style="width: 120px;margin-bottom: 20px;" :disabled="optimizerSelectDisable">
        <a-select-option :value="0">
          全部
        </a-select-option>
        <a-select-option :value="item.id" v-for="(item,index) in optimizerList" :key="index">
          {{item.username}}
        </a-select-option> 
      </a-select>
      <!-- <a-button @click="copy" style="margin-left: 20px;">复制计划</a-button> -->
      <standard-table
        rowKey="campaignId"
        :loading='loading'
        :columns="columns"
        :dataSource="dataSource"
        :selectedRows.sync="selectedRowKeys"
        :scroll="{x:1200}"
        :pagination="{showTotal:total => `共 ${total} 条数据`}"
        @change="onChange"
        @selectedRowChange="selectedRowChange"
      >
        <div slot="ctr" slot-scope="{record}">
          {{(record.ctr*100).toFixed(2) + '%'}}
        </div>
        <div slot="cost" slot-scope="{record}">
          {{(record.cost).toFixed(2)}}
        </div>
      </standard-table>
    </a-card>  
    <a-modal v-model="showChooseZhanghu" title="选择目标账号" :width="600" okText="复制" @ok="fuzhi" :confirm-loading="fuzhiLoading">
      <a-input-search placeholder="搜索目标账号" enter-button @search="onFuzhiSearch" style="margin-bottom:20px;" />
      <a-checkbox-group @change="onZhanghaoChange" style="width: 100%;max-height: 600px;overflow-y: auto;">
        <a-row>
          <a-col :span="8" v-for="(item,index) in zhanghaoId" :key="index">
            <!-- <a-checkbox :value="item.id" v-if="item.name == storeName" style="color:#1890ff;">{{item.name}}(本账户)</a-checkbox> -->
            <a-checkbox :value="item.id" >{{item.name}}</a-checkbox>
          </a-col>
        </a-row>
      </a-checkbox-group>
    </a-modal>
  </div>
</template>

<script>
import { getAmountTakeoff } from '@/api/dianshang/dianshang'
import StandardTable from '@/components/table/StandardTable'
import {getOptimizerList} from '@/api/xinxiliu/account'
import { getBdAccountList } from '@/api/xinxiliu/account'

// const dataSource = [
//   {act: 148.5,bact: 124.534375,campaignId: 231617032,campaignNameStatus: "10.10-夏果-通投-手百ocpc程序化pRbRA1211911107（有效）",click: 63,cost: 148.5,cpc: 2.3571428571429,cpm: 22.772580892501,ctLiveOrderConversions: 0,ctProductPaySuccess: 8,ctProductPaySuccessAmount: 89,ctProductPaySuccessAmountROI: 0.5993265993266,ctr: 0.0096610949240914,date: "2022-10-26",diff: 23.965625000000003,id: 1215671,impression: 6521,liveCost: 0,liveOrderConversionsCost: 0,pct: 89,sales: 1,userName: "祺鑫百货店69（邹颖）", firstOrderTime: '2022-10-26 10:51:18'},
// ]

const columns = [
  // {
  //   title: '推广计划',
  //   width: 600,
  //   dataIndex: 'campaignNameStatus',
  // },
  {
    title: '账户',
    width: 200,
    dataIndex: 'userName'
  },
  {
    title: '计划名称',
    width: 240,
    dataIndex: 'campaignNameStatus'
  },
  {
    title: '展现',
    width: 100,
    dataIndex: 'impression',
    sortDirections:['descend','ascend'],
    sorter: () => {},
  },
  {
    title: '点击',
    width: 100,
    dataIndex: 'click',
    sortDirections:['descend','ascend'],
    sorter: () => {},
  },
  {
    title: '消费',
    width: 100,
    dataIndex: 'cost',
    scopedSlots: { customRender: 'cost' },
    sortDirections:['descend','ascend'],
    sorter: () => {},
  },
  {
    title: '点击率',
    width: 100,
    dataIndex: 'ctr',
    scopedSlots: { customRender: 'ctr' },
    sortDirections:['descend','ascend'],
    sorter: () => {},
  },
  {
    title: '商品支付成功量',
    width: 200,
    defaultSortOrder: 'descend',
    dataIndex: 'dsOcpcConversionsDetail90',
    sortDirections:['descend','ascend'],
    sorter: () => {},
  },
  {
    title: '直播间成单量',
    width: 200,
    dataIndex: 'dsOcpcConversionsDetail80',
    scopedSlots: { customRender: 'ctLiveOrderConversions' },
    sortDirections:['descend','ascend'],
    sorter: () => {},
  },
  {
    title: '首单成交时间',
    width: 200,
    dataIndex: 'firstOrderTime',
    scopedSlots: { customRender: 'firstOrderTime' },
  }
]
export default {
  data() {
    return {
      columns,
      loading:false,
      dataSource:[],
      total:0,
      changeKey:'dsOcpcConversionsDetail90',
      changeOrder:'DESC',
      optimizer:0,
      optimizerList:[],
      optimizerSelectDisable:false,
      selectedRowKeys:[],
      showChooseZhanghu:false,
      zhanghaoId:[],
      zhanghaoIdToatal:[],
      toZhanghaoId:[],
      fuzhiLoading: false,

    }
  },
  created(){
    this.getQiliangData()
    this.getOptimizerList()
  },
  methods:{
    getQiliangData(){
      let params = {
        column:this.changeKey,
        sortrule:this.changeOrder,
      }
      if(this.optimizer != 0){
        params.optimizer = this.optimizer
      }
      this.loading = true
      getAmountTakeoff(params).then((res) => {
        this.loading = false
        if(res.errcode == 0){
          this.dataSource = this.dataSource.concat(res.data)
          this.total = res.data.length
        }
      }).catch(() => {
        this.loading = false
      });
    },
    getSorter(sorter){
      if(sorter.column){
        this.changeKey = sorter.column.dataIndex
        switch(sorter.order){
          case "ascend":
            this.changeOrder = 'ASC'
            break
          case "descend":
            this.changeOrder = 'DESC'
            break
        }
      }else{
        this.changeKey = ''
        this.changeOrder = ''
      }
    },
    fuzhi(){
      if(this.toZhanghaoId.length > 0){
        this.showChooseZhanghu = false
        this.$message.success('复制成功')
      }
    },
    getOptimizerList(){
      getOptimizerList({}).then((res) => {
        if(res.errcode == 0){
          this.optimizerList = res.data
          this.setOptimizer()
        }
      }).catch(() => {
        
      })
    },
    selectChange(){
      this.getQiliangData()
    },
    setOptimizer(){
      // 判断当前登录账号是否优化师，是则不允许选择搜索只能看自己的
      let userInfo = this.$store.state.user.userInfo
      if(userInfo){
        let isoptimizer = userInfo.isoptimizer // 0不是， 1是优化师
        if(isoptimizer == 1){
          let admin_user_id = userInfo.admin_user_id
          let f = this.optimizerList.find(e=>e.id == admin_user_id)
          if(f){
            this.optimizer = admin_user_id
            this.optimizerSelectDisable = true
          }
        }
      }
    },
    copy(){
      let selectedRowsForId = this.selectedRowsForId
      if(selectedRowsForId.length > 0){
        this.showChooseZhanghu = true
        getBdAccountList({}).then((res) => {
          if(res.errcode == 0){
            let data = res.data.filter(e=>e.pid > 0)
            let zhanghaoId = data.map(e=>{
              return {
                name:e.account,
                id:e.id
              }
            })
            this.zhanghaoId = zhanghaoId
            this.zhanghaoIdToatal = zhanghaoId
          }
        });
      }else{
        this.$message.error('请选择需要复制的计划')
      }
    },
    selectedRowChange(selectedRowKeys, selectedRows){
      console.log('selectedRowChange',selectedRowKeys, selectedRows)
      this.selectedRowsForId = selectedRows.map(e=>e.campaignFeedId)
    },
    onZhanghaoChange(e){
      this.toZhanghaoId = e
    },
    onFuzhiSearch(e){
      let zhanghaoIdToatal = JSON.parse(JSON.stringify(this.zhanghaoIdToatal))
      if(e != ""){
        this.zhanghaoId = zhanghaoIdToatal.filter(o=>o.name.indexOf(e) != -1)
      }else{
        this.zhanghaoId = zhanghaoIdToatal
      }
    },
    onChange(pagination, filters, sorter,) {
      // console.log(pagination, filters, sorter)
      this.getSorter(sorter)
      this.page = pagination.current
      this.getQiliangData()
    },
  },
  components:{StandardTable}
}
</script>

<style lang="less" scoped>

</style>